package com.xiaohan.usercenter.exception;

import com.xiaohan.usercenter.common.BaseResponse;
import com.xiaohan.usercenter.common.ResultUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static com.xiaohan.usercenter.common.ErrorCode.SYSTEM_ERROR;

/**
 * @program: backend
 * @description: 全局异常捕获及处理
 * @author: 韩小豪
 * @create: 2025-02-28 08:39
 **/

@RestControllerAdvice  //捕获控制层中出现的所有异常
@Slf4j
public class GlobalExceptionHandler {

	/**
	 * 捕获及处理自定义异常
	 */
	@ExceptionHandler(value = CustomException.class)
	public BaseResponse customExceptionHandler(CustomException e) {
		log.error("CustomException:{}",e.getDescription());
		return ResultUtils.error(e.getCode(), e.getMessage(), e.getDescription());
	}

	/**
	 * 捕获java内部异常
	 * 统一返回系统异常
	 */
	@ExceptionHandler(value = RuntimeException.class)
	public BaseResponse runtimeExceptionHandler(RuntimeException e) {
		log.error("RuntimeException:{}", e.getMessage());
		return ResultUtils.error(SYSTEM_ERROR, e.getMessage(), "");
	}
}
